const router = require('koa-router')()
const mongoose = require('mongoose')
const util = require('util');
const fs = require('fs')
const stats = require('../helpers/stats')
const popular = require('../helpers/popular')
const latestComments = require('../helpers/comments')
const checkToken = require('../helpers/checkToken')

const Image = mongoose.model('Image')

router.get('/', async (ctx, next) => {
    var token = ctx.cookies.get('token')
    await Promise.all([
        Image.find({}).sort({timestamp : -1}),
        stats(),
        popular(),
        latestComments(),
        checkToken(token)
    ])
    .then(([images,stats,popular,latestComments,loginAbout]) => ctx.render('index', {
        images: images,
        stats:stats,
        popular:popular,
        latestComments:latestComments,
        loginAbout:loginAbout
    }))
    .catch(err => ctx.throw(500, err))
})


module.exports = router
